let selectedFiles = [];
let uploadedFiles = [];
let currentResult = null;
let currentImageFile = null;
let textBoxesVisible = false;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeUpload();
    loadFileHistory();
});

// 添加全局快捷键支持
document.addEventListener('keydown', function(e) {
    // Ctrl+H 切换文本框显示/隐藏
    if (e.ctrlKey && e.key === 'h') {
        e.preventDefault();
        toggleTextBoxes();
    }
    
    // Ctrl+C 复制结果（当没有选中文本时）
    if (e.ctrlKey && e.key === 'c' && window.getSelection().toString() === '') {
        const activeElement = document.activeElement;
        if (!activeElement.classList.contains('text-input-box')) {
            e.preventDefault();
            copyResult();
        }
    }
    
    // Ctrl+S 下载结果
    if (e.ctrlKey && e.key === 's') {
        e.preventDefault();
        downloadResult();
    }
    
    // Escape 退出所有编辑模式
    if (e.key === 'Escape') {
        const editingBoxes = document.querySelectorAll('.text-input-box:not([readonly])');
        editingBoxes.forEach(box => {
            box.blur();
        });
    }
});

// 初始化上传功能
function initializeUpload() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');

    // 拖拽上传
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });

    uploadArea.addEventListener('dragleave', function(e) {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
    });

    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        const files = Array.from(e.dataTransfer.files);
        handleFiles(files);
    });

    // 文件选择
    fileInput.addEventListener('change', function(e) {
        const files = Array.from(e.target.files);
        handleFiles(files);
    });

    // 全选功能
    document.getElementById('selectAll').addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.file-item input[type="checkbox"]');
        checkboxes.forEach(cb => cb.checked = this.checked);
        updateSelectedCount();
    });
}

// 选择文件
function selectFiles() {
    document.getElementById('fileInput').click();
}

// 处理文件
function handleFiles(files) {
    const validFiles = files.filter(file => {
        const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/bmp', 'image/tiff', 'image/gif', 'application/pdf'];
        const maxSize = 5 * 1024 * 1024; // 5MB
        
        if (!validTypes.includes(file.type)) {
            alert(`文件 ${file.name} 格式不支持`);
            return false;
        }
        
        if (file.size > maxSize) {
            alert(`文件 ${file.name} 超过5MB大小限制`);
            return false;
        }
        
        return true;
    });

    selectedFiles = [...selectedFiles, ...validFiles];
    displayFiles();
    
    if (selectedFiles.length > 0) {
        document.getElementById('fileControls').style.display = 'block';
    }
}

// 显示文件列表
function displayFiles() {
    const fileList = document.getElementById('fileList');
    
    if (selectedFiles.length === 0 && uploadedFiles.length === 0) {
        fileList.innerHTML = '<p class="no-files">暂未上传过任何文件</p>';
        return;
    }
    
    let html = '';
    
    // 显示已选择的文件
    selectedFiles.forEach((file, index) => {
        html += createFileItemHTML(file, index, false);
    });
    
    // 显示已上传的文件
    uploadedFiles.forEach((file, index) => {
        html += createFileItemHTML(file, index, true);
    });
    
    fileList.innerHTML = html;
    updateSelectedCount();
}

// 创建文件项HTML
function createFileItemHTML(file, index, isUploaded) {
    const fileName = file.name || file.filename;
    const fileSize = file.size || 0;
    const status = isUploaded ? 'uploaded' : 'selected';
    const statusText = isUploaded ? '已上传' : '待上传';
    
    return `
        <div class="file-item ${status}">
            <input type="checkbox" ${!isUploaded ? 'checked' : ''}>
            <div class="file-info">
                <div class="file-name">${fileName}</div>
                <div class="file-meta">
                    <span class="file-size">${formatFileSize(fileSize)}</span>
                    <span class="file-status">${statusText}</span>
                </div>
            </div>
            <button class="remove-btn" onclick="removeFile(${index}, ${isUploaded})">×</button>
        </div>
    `;
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 移除文件
function removeFile(index, isUploaded) {
    if (isUploaded) {
        uploadedFiles.splice(index, 1);
    } else {
        selectedFiles.splice(index, 1);
    }
    displayFiles();
    
    if (selectedFiles.length === 0) {
        document.getElementById('fileControls').style.display = 'none';
    }
}

// 更新选中文件数量
function updateSelectedCount() {
    const checkedBoxes = document.querySelectorAll('.file-item input[type="checkbox"]:checked');
    document.getElementById('selectedCount').textContent = `已经选${checkedBoxes.length}个文件`;
}

// 处理文件（OCR识别）
async function processFiles() {
    const checkedBoxes = document.querySelectorAll('.file-item input[type="checkbox"]:checked');
    const filesToProcess = [];
    
    checkedBoxes.forEach((checkbox, index) => {
        const fileItem = checkbox.closest('.file-item');
        const isUploaded = fileItem.classList.contains('uploaded');
        
        if (!isUploaded) {
            // 找到对应的文件
            const fileIndex = Array.from(fileItem.parentNode.children).indexOf(fileItem);
            const selectedFileIndex = fileIndex - uploadedFiles.length;
            if (selectedFileIndex >= 0 && selectedFiles[selectedFileIndex]) {
                filesToProcess.push(selectedFiles[selectedFileIndex]);
            }
        }
    });
    
    if (filesToProcess.length === 0) {
        alert('请选择要处理的文件');
        return;
    }
    
    showLoading(true);
    
    try {
        if (filesToProcess.length === 1) {
            // 单文件处理
            const file = filesToProcess[0];
            currentImageFile = file;
            
            // 显示图片预览
            displayImagePreview(file);
            
            const formData = new FormData();
            formData.append('file', file);
            
            const response = await fetch('/api/ocr', {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            
            if (result.success) {
                currentResult = result;
                displayResult(result);  // 这里会调用generateTextBoxes
                updateImageInfo(file, result);
                // 移除重复的generateTextBoxes调用
                
                // 移动到已上传列表
                uploadedFiles.unshift({
                    name: file.name,
                    size: file.size,
                    result: result
                });
                
                // 从选中列表移除
                const fileIndex = selectedFiles.indexOf(file);
                if (fileIndex > -1) {
                    selectedFiles.splice(fileIndex, 1);
                }
                
                displayFiles();
            } else {
                alert('识别失败: ' + result.error);
                updateImageInfo(file, { success: false, error: result.error });
            }
        } else {
            // 批量处理
            const formData = new FormData();
            filesToProcess.forEach(file => {
                formData.append('files', file);
            });
            
            const response = await fetch('/api/batch_ocr', {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            
            if (result.success) {
                // 显示批量结果
                let combinedText = '';
                result.results.forEach((r, index) => {
                    if (r.success) {
                        combinedText += `=== 文件 ${index + 1}: ${r.filename} ===\n${r.text}\n\n`;
                    } else {
                        combinedText += `=== 文件 ${index + 1}: ${r.filename} ===\n错误: ${r.error}\n\n`;
                    }
                });
                
                currentResult = {
                    text: combinedText,
                    batch: true,
                    summary: result.summary
                };
                displayResult(currentResult);
                
                // 移动成功的文件到已上传列表
                result.results.forEach((r, index) => {
                    if (r.success) {
                        uploadedFiles.unshift({
                            name: filesToProcess[index].name,
                            size: filesToProcess[index].size,
                            result: r
                        });
                    }
                });
                
                // 清空选中列表
                selectedFiles = [];
                displayFiles();
            } else {
                alert('批量识别失败: ' + result.error);
            }
        }
    } catch (error) {
        alert('请求失败: ' + error.message);
    } finally {
        showLoading(false);
    }
}

// 显示结果
function displayResult(result) {
    document.getElementById('resultSection').style.display = 'block';
    document.getElementById('resultText').textContent = result.text;
    document.getElementById('resultJson').textContent = JSON.stringify(result, null, 2);
    
    // 生成文本框
    generateTextBoxes(result);
    
    // 滚动到结果区域
    document.getElementById('resultSection').scrollIntoView({ behavior: 'smooth' });
}

// 切换结果标签
function switchTab(tab) {
    document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
    document.querySelectorAll('.result-panel').forEach(panel => panel.classList.remove('active'));
    
    document.querySelector(`[onclick="switchTab('${tab}')"]`).classList.add('active');
    document.getElementById(tab + 'Result').classList.add('active');
}

// 复制结果
function copyResult() {
    const activePanel = document.querySelector('.result-panel.active');
    let text = '';
    
    if (activePanel.id === 'previewResult') {
        // 如果是预览标签，复制识别结果文本
        text = currentResult ? currentResult.text : '';
    } else {
        text = activePanel.textContent;
    }
    
    if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
            alert('结果已复制到剪贴板');
        }).catch(() => {
            // 降级方案
            const textarea = document.createElement('textarea');
            textarea.value = text;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
            alert('结果已复制到剪贴板');
        });
    } else {
        // 降级方案
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        alert('结果已复制到剪贴板');
    }
}

// 下载结果
function downloadResult() {
    if (!currentResult) {
        alert('没有可下载的结果');
        return;
    }
    
    const text = currentResult.text;
    const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = `ocr_result_${new Date().getTime()}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// 显示/隐藏加载动画
function showLoading(show) {
    document.getElementById('loading').style.display = show ? 'flex' : 'none';
}

// 显示图片预览
function displayImagePreview(file) {
    const previewImage = document.getElementById('previewImage');
    const previewPlaceholder = document.getElementById('previewPlaceholder');
    
    if (file && file.type.startsWith('image/')) {
        const reader = new FileReader();
        reader.onload = function(e) {
            previewImage.src = e.target.result;
            previewImage.style.display = 'block';
            previewPlaceholder.style.display = 'none';
        };
        reader.readAsDataURL(file);
    } else {
        previewImage.style.display = 'none';
        previewPlaceholder.style.display = 'block';
        previewPlaceholder.textContent = file ? '不支持预览此文件类型' : '暂无图片预览';
    }
}

// 生成文本框（使用OCR API返回的真实坐标）- 优化版本
function generateTextBoxes(result) {
    const textBoxesContainer = document.getElementById('textBoxes');
    textBoxesContainer.innerHTML = '';
    
    console.log('🔍 开始自动定位文本框，OCR Result:', result);
    
    if (!result.text) {
        console.log('❌ 没有识别到文本');
        return;
    }
    
    const previewImage = document.getElementById('previewImage');
    if (!previewImage) {
        console.log('❌ 找不到预览图片元素');
        return;
    }
    
    // 等待图片加载完成后生成文本框
    const generateBoxes = function() {
        console.log('🖼️ 开始自动定位文本框');
        
        // 设置文本框容器
        textBoxesContainer.style.display = 'block';
        textBoxesContainer.style.position = 'absolute';
        textBoxesContainer.style.top = '0';
        textBoxesContainer.style.left = '0';
        textBoxesContainer.style.width = '100%';
        textBoxesContainer.style.height = '100%';
        textBoxesContainer.style.pointerEvents = 'auto';
        textBoxesContainer.style.zIndex = '50';
        
        // 检查是否有真实的TextOverlay数据
        const textOverlay = result.text_overlay;
        const hasRealCoordinates = textOverlay && 
                                  textOverlay.Lines && 
                                  Array.isArray(textOverlay.Lines) && 
                                  textOverlay.Lines.length > 0 &&
                                  !textOverlay.Message; // 排除模拟数据
        
        console.log('📍 坐标数据检查:', { 
            hasRealCoordinates, 
            textOverlay: textOverlay 
        });
        
        if (!hasRealCoordinates) {
            console.log('❌ 没有真实的坐标数据，无法自动定位');
            
            // 显示提示信息
            const tipDiv = document.createElement('div');
            tipDiv.className = 'coordinate-tip';
            tipDiv.innerHTML = `
                <div style="
                    position: absolute;
                    top: 10px;
                    left: 10px;
                    background: rgba(255, 193, 7, 0.9);
                    color: #856404;
                    padding: 8px 12px;
                    border-radius: 6px;
                    font-size: 12px;
                    border: 1px solid #ffeaa7;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                    z-index: 1000;
                ">
                    <i class="fas fa-info-circle"></i> 
                    需要坐标数据才能精确定位文本框
                </div>
            `;
            textBoxesContainer.appendChild(tipDiv);
            
            setTimeout(() => {
                if (tipDiv.parentNode) {
                    tipDiv.parentNode.removeChild(tipDiv);
                }
            }, 3000);
            
            textBoxesVisible = false;
            return;
        }
        
        // 使用真实的OCR坐标数据进行精确定位
        console.log('✅ 使用真实坐标数据进行自动定位');
        
        // 获取图片的实际显示尺寸和原始尺寸
        const imageRect = previewImage.getBoundingClientRect();
        const containerRect = previewImage.parentElement.getBoundingClientRect();
        
        // 计算图片在容器中的实际位置和缩放比例
        const scaleX = previewImage.clientWidth / previewImage.naturalWidth;
        const scaleY = previewImage.clientHeight / previewImage.naturalHeight;
        
        // 计算图片相对于容器的偏移
        const offsetX = (previewImage.clientWidth - previewImage.naturalWidth * scaleX) / 2;
        const offsetY = (previewImage.clientHeight - previewImage.naturalHeight * scaleY) / 2;
        
        console.log('📐 图片信息:', {
            显示尺寸: { width: previewImage.clientWidth, height: previewImage.clientHeight },
            原始尺寸: { width: previewImage.naturalWidth, height: previewImage.naturalHeight },
            缩放比例: { scaleX, scaleY },
            偏移量: { offsetX, offsetY }
        });
        
        let textBoxCount = 0;
        const createdBoxes = []; // 存储已创建的文本框信息，用于避免重叠
        
        // 处理每一行文本 - 只创建单词级别的文本框，不创建大框
        textOverlay.Lines.forEach((line, lineIndex) => {
            if (line.Words && Array.isArray(line.Words) && line.Words.length > 0) {
                
                // 为每个单词创建独立的文本框（更精确）
                line.Words.forEach((word, wordIndex) => {
                    if (word.Left !== undefined && word.Top !== undefined && 
                        word.Width !== undefined && word.Height !== undefined && 
                        word.WordText && word.WordText.trim()) {
                        
                        // 计算精确的坐标
                        const left = word.Left * scaleX + offsetX;
                        const top = word.Top * scaleY + offsetY;
                        const width = Math.max(word.Width * scaleX, 20);
                        const height = Math.max(word.Height * scaleY, 15);
                        
                        // 检查是否与已有文本框重叠
                        const isOverlapping = createdBoxes.some(box => {
                            return !(left > box.right || 
                                   left + width < box.left || 
                                   top > box.bottom || 
                                   top + height < box.top);
                        });
                        
                        if (!isOverlapping) {
                            const textBox = createTextBox({
                                text: word.WordText.trim(),
                                left: left,
                                top: top,
                                width: width,
                                height: height,
                                index: `${lineIndex}-${wordIndex}`,
                                type: 'word'
                            });
                            
                            textBoxesContainer.appendChild(textBox);
                            
                            // 记录文本框位置信息
                            createdBoxes.push({
                                left: left,
                                top: top,
                                right: left + width,
                                bottom: top + height
                            });
                            
                            textBoxCount++;
                            
                            console.log(`📍 创建单词文本框 ${lineIndex}-${wordIndex}:`, {
                                原始坐标: { left: word.Left, top: word.Top, width: word.Width, height: word.Height },
                                显示坐标: { left, top, width, height },
                                文本: word.WordText.trim()
                            });
                        }
                    }
                });
            }
        });
        
        console.log(`✅ 文本框生成完成，共创建 ${textBoxCount} 个文本框`);
        textBoxesVisible = true;
        
        // 显示统计信息
        setTimeout(() => {
            const statsDiv = document.createElement('div');
            statsDiv.style.cssText = `
                position: absolute;
                top: 10px;
                right: 10px;
                background: rgba(40, 167, 69, 0.9);
                color: white;
                padding: 6px 10px;
                border-radius: 4px;
                font-size: 11px;
                z-index: 1000;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            `;
            statsDiv.innerHTML = `📍 定位框: ${textBoxCount}个`;
            textBoxesContainer.appendChild(statsDiv);
            
            setTimeout(() => {
                if (statsDiv.parentNode) {
                    statsDiv.parentNode.removeChild(statsDiv);
                }
            }, 2000);
        }, 500);
    };
    
    // 如果图片已经加载完成，直接生成文本框
    if (previewImage.complete && previewImage.naturalHeight !== 0) {
        generateBoxes();
    } else {
        // 否则等待图片加载完成
        previewImage.addEventListener('load', generateBoxes);
    }
}

// 创建文本框的辅助函数
function createTextBox(options) {
    const { text, left, top, width, height, index, type } = options;
    
    const textInput = document.createElement('div'); // 改为div元素，不再是input
    textInput.className = `text-input-box text-box-${type}`;
    textInput.title = `${type === 'word' ? '单词' : '行'}文本框 ${index}`;
    textInput.dataset.index = index;
    textInput.dataset.type = type;
    textInput.dataset.originalText = text; // 保存原始文本用于其他功能
    
    // 设置精确的样式 - 仅用于定位，不显示文字
    textInput.style.position = 'absolute';
    textInput.style.top = Math.round(top) + 'px';
    textInput.style.left = Math.round(left) + 'px';
    textInput.style.width = Math.round(width) + 'px';
    textInput.style.height = Math.round(height) + 'px';
    textInput.style.zIndex = '100';
    textInput.style.border = type === 'word' ? '1px solid #007bff' : '2px solid #007bff';
    textInput.style.background = 'rgba(0, 123, 255, 0.1)'; // 稍微增加透明度以便看到定位
    textInput.style.borderRadius = '3px';
    textInput.style.outline = 'none';
    textInput.style.transition = 'all 0.15s ease';
    textInput.style.cursor = 'pointer';
    textInput.style.boxShadow = '0 1px 2px rgba(0,0,0,0.08)';
    textInput.style.boxSizing = 'border-box';
    textInput.style.pointerEvents = 'auto';
    
    // 不显示任何文字内容
    textInput.innerHTML = '';
    
    // 添加悬停效果
    textInput.addEventListener('mouseenter', function() {
        this.style.borderColor = '#28a745';
        this.style.background = 'rgba(40, 167, 69, 0.15)';
        this.style.boxShadow = '0 2px 4px rgba(0,0,0,0.12)';
    });
    
    textInput.addEventListener('mouseleave', function() {
        this.style.borderColor = '#007bff';
        this.style.background = 'rgba(0, 123, 255, 0.1)';
        this.style.boxShadow = '0 1px 2px rgba(0,0,0,0.08)';
    });
    
    // 点击时显示文本内容（可选功能）
    textInput.addEventListener('click', function() {
        console.log(`文本框 ${index} 内容:`, text);
    });
    
    return textInput;
}

// 切换文本框显示
function toggleTextBoxes() {
    const textBoxes = document.getElementById('textBoxes');
    const toggleIcon = document.getElementById('toggleIcon');
    const toggleText = document.getElementById('toggleText');
    
    textBoxesVisible = !textBoxesVisible;
    
    if (textBoxesVisible) {
        textBoxes.style.display = 'block';
        toggleIcon.className = 'fas fa-eye-slash';
        toggleText.textContent = '隐藏文本框';
    } else {
        textBoxes.style.display = 'none';
        toggleIcon.className = 'fas fa-eye';
        toggleText.textContent = '显示文本框';
    }
}

// 添加批量操作功能
function selectAllTextBoxes() {
    const textBoxes = document.querySelectorAll('.text-input-box');
    textBoxes.forEach(box => {
        box.style.borderColor = '#ffc107';
        box.style.background = 'rgba(255, 193, 7, 0.1)';
    });
    
    setTimeout(() => {
        textBoxes.forEach(box => {
            if (box.readOnly) {
                box.style.borderColor = '#007bff';
                box.style.background = 'rgba(0, 123, 255, 0.08)';
            }
        });
    }, 1000);
}

// 添加文本框统计信息
function showTextBoxStats() {
    const textBoxes = document.querySelectorAll('.text-input-box');
    const totalChars = Array.from(textBoxes).reduce((sum, box) => sum + box.value.length, 0);
    
    console.log('📊 文本框统计:', {
        文本框数量: textBoxes.length,
        总字符数: totalChars,
        平均字符数: Math.round(totalChars / textBoxes.length)
    });
}

// 更新图片信息
function updateImageInfo(file, result) {
    document.getElementById('fileName').textContent = file.name;
    document.getElementById('fileSize').textContent = formatFileSize(file.size);
    
    if (result.success) {
        document.getElementById('ocrStatus').textContent = '识别成功';
        document.getElementById('ocrStatus').style.color = '#28a745';
    } else {
        document.getElementById('ocrStatus').textContent = '识别失败';
        document.getElementById('ocrStatus').style.color = '#dc3545';
    }
}

// 加载文件历史
function loadFileHistory() {
    // 这里可以从localStorage或服务器加载历史文件
    const history = JSON.parse(localStorage.getItem('ocrFileHistory') || '[]');
    uploadedFiles = history;
    displayFiles();
}

// 保存文件历史
function saveFileHistory() {
    localStorage.setItem('ocrFileHistory', JSON.stringify(uploadedFiles));
}

// 更新结果文本
function updateResultText() {
    const textInputs = document.querySelectorAll('.text-input-box');
    const updatedText = Array.from(textInputs).map(input => input.value).filter(text => text.trim()).join('\n');
    
    // 更新结果显示区域
    const resultText = document.getElementById('resultText');
    if (resultText) {
        resultText.textContent = updatedText;
    }
    
    // 更新当前结果
    if (currentResult) {
        currentResult.text = updatedText;
    }
}

// 页面卸载时保存历史
window.addEventListener('beforeunload', saveFileHistory);